﻿using SoundEngine3.MIDI.Meta;
using System;

namespace ZquenceStudio3Host.DspPlugins.Synthesizers.Nodesizer.Engine.Modules.LowLevel.Midi
{
    [ModuleDisplay("Midi Pitch")]
    class MidiPitchModule : BaseModule
    {
        public readonly ModuleParameter ParameterOctave;
        public readonly ModuleParameter ParameterNote;
        public readonly ModuleParameter ParameterTune;

        public readonly ModuleInput In;
        public readonly ModuleOutput Out;

        public MidiPitchModule(ModuleManager manager)
            : base(manager)
        {
            // Add input and outputs to module.
            AddInput(In = new ModuleInput("In", IOType.Midi, this));
            AddOutput(Out = new ModuleOutput("Out", IOType.Midi, this));

            ParameterOctave = new ModuleParameter(this);
            ParameterOctave.Label = "Note";
            ParameterOctave.MinValue = -7;
            ParameterOctave.MaxValue = 7;
            ParameterOctave.RawValue = 0;
            AddParameter(ParameterOctave);

            ParameterNote = new ModuleParameter(this);
            ParameterNote.Label = "Note";
            ParameterNote.MinValue = -12;
            ParameterNote.MaxValue = 12;
            ParameterNote.RawValue = 0;
            AddParameter(ParameterNote);

            ParameterTune = new ModuleParameter(this);
            ParameterTune.Label = "Tune";
            ParameterTune.MinValue = -64;
            ParameterTune.MaxValue = 63;
            ParameterTune.RawValue = 0;
            AddParameter(ParameterTune);

        }

        public override void Process()
        {
            // First check if both inputs sources is connected.
            if (In.IsConnected)
            {
                foreach (var message in In.FromOutput.MidiBuffer)
                {
                    MidiMessage newMessage = message;
                    newMessage.MidiData.Parameter1 += (byte)Math.Max(0, Math.Min(120, ParameterNote.RawValue + ParameterOctave.RawValue * 12));
                    newMessage.Detune = (short)ParameterTune.RawValue;
                    Out.AddMidiMessage(newMessage);
                }
            }
        }
    }
}
